import React, { Component } from "react";

import { connect } from "react-redux";

const mapDispatchToProps = (dispatch) => {
  return {
    addItem(value) {
      dispatch({
        type: "addItem",
        payload: { name: value, id: new Date().getTime() },
      });
    },
  };
};

class Form extends Component {
  state = {
    value: "",
  };

  handleChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  };

  handleClick = () => {
    if (this.state.value) {
      this.props.addItem(this.state.value);
      this.setState({
        value: "",
      });
    }
  };

  render() {
    return (
      <>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
        />
        <button onClick={this.handleClick}>添加</button>
      </>
    );
  }
}

export default connect(null, mapDispatchToProps)(Form);
